import axios from 'axios'
import qs from 'qs'
import Toast from "./Toast"


axios.defaults.withCredentials = true
//axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'
axios.defaults.timeout = 10000

axios.interceptors.request.use((config) => {
  Toast.loadingToast();
  return config;  //添加这一行
}, (error) => {
  return Promise.reject(error);
});

// axios拦截器
axios.interceptors.response.use(response => {
  Toast.closeToast();
  // 在这里你可以判断后台返回数据携带的请求码
  if (response && response.status === 200) {
    //successToast();
    return response.data.data || response.data
  } else {
    if (response && response.data && response.data.msg) {
      Toast.failToast(response.data.msg)
    }
    // 非200请求抱错
    throw Error(response.data.msg || '服务异常')
  }
})

function checkStatus (response) {
  // 如果状态码正常就直接返回数据,这里的状态码是htttp响应状态码有400，500等，不是后端自定义的状态码
  if (response && ((response.status === 200 || response.status === 304 || response.status === 400))) {
    return response.data // 直接返回http response响应的data,此data会后端返回的数据数据对象，包含后端自定义的code,message,data属性
  }
  return { // 自定义网络异常对象
    code: '404',
    message: '网络异常'
  }
}

export default {
  axios,
  post(url, data) {
    return axios({
      method: 'post',
      baseURL: process.env.BASE_URL,
      url: url,
      data: qs.stringify(data),
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      },
      timeout: 10000
    })
  },
  get(url, params) {
    return axios({
      method: 'get',
      baseURL: process.env.BASE_URL,
      url,
      params,
      timeout: 10000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest'
      }
    })
  }
}
//export default axios
